
/**
 * 生成枚举 支持传入对象，和数组。会给该对象或数组添加工具方法和属性。 _options, _getLabel, _getActiveByKey
 * @param {Array | Object} obj {key: '---', label: '---'}
 * @returns Proxy {_options, _getLabel, _getActiveByKey}
 */
const generateEnum = (obj) => {
    const isArray = Object.prototype.toString.call(obj) === '[object Array]';
    const isObject = Object.prototype.toString.call(obj) === '[object Object]';
    if(!isArray && !isObject) return obj;
    const noEnumList = ['options', 'getLabel', 'getActiveByKey']
    const newObj = new Proxy(obj, {
        defineProperty(target, key, descriptor) {
            if(noEnumList.includes(key)) {
                descriptor.enumerable = false;
            }
            return Reflect.defineProperty(target, key, descriptor);
        },
        get(target, prop, receiver) {
            let list = target;
            if(isObject) {
                list = Object.values(target);
            }
            if(prop === '_options') {
                return list;
            }
            if(prop === '_getLabel') {
                return (key, slotStr) => {
                    let active = list.find(v => v.key === key)
                    return active?.label || slotStr
                }
            }
            if(prop === '_getActiveByKey') {
                list.find(v => v.key === key)
            }
            return Reflect.get(...arguments);
        }
    })


    return newObj;
}
export default  generateEnum